<template>
  <!-- 今日报警 -->
  <echartsChart ref="alarmStatRef" :dark="dark" :arrow="arrow" :title="title" :options="alarmStatOptions" :titleBgWidth="150" @btn-click="toPage" />
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { useLabelLayoutBarChartFn, useGetBarChartsAgOptions } from "@/hooks/useEcharts";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { queryAlarmCount } from "@/api/alert";

interface Props {
  classCode: string;
  height?: number;
  dark?: boolean;
  arrow?: boolean;
  title?: string;
}

const props = withDefaults(defineProps<Props>(), { height: 234, dark: false, arrow: false, title: "今日报警" });
const router = useRouter();
// 设备状态

// 今日报警
const alarmStatRef = ref<InstanceType<typeof echartsChart> | null>(null);
const alarmStatOptions = ref<CommonEcharts.CommonEchartsOption | null>(null);
const startTime = dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss");
const endTime = dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss");
const toPageMap = new Map([
  [
    "总报警",
    {
      path: "/all/alert/business",
      query: { className: props.classCode, active: "ALL", startTime, endTime }
    }
  ],
  [
    "已解决",
    {
      path: "/all/alert/business",
      query: { className: props.classCode, active: "DONE", startTime, endTime }
    }
  ],
  [
    "待解决",
    {
      path: "/all/alert/business",
      query: { className: props.classCode, active: "UNDO", startTime, endTime }
    }
  ]
]);

const alarmStatInit = async () => {
  const alarmStat = await queryAlarmCount({ alarmCenterFlag: "YES", className: props.classCode, startTime, endTime });
  if (!alarmStat) return;
  const { totalNumber = 0, undoNumber = 0, doneNumber = 0 } = alarmStat;
  const ec = await alarmStatRef.value.getEcharts();
  const xAxisData = ["待解决", "已解决", "总报警"];
  const data = [undoNumber, doneNumber, totalNumber];
  const colorList = ["#FECD4B", "#19D08D", "#F45252"];
  const ag = useGetBarChartsAgOptions(xAxisData, data, true, "", colorList, 22);
  alarmStatOptions.value = useLabelLayoutBarChartFn(ec, xAxisData, data, props.title, "", colorList, false, "", ag);
  // alarmStatRef.value.loadingInstance.close();
  if (!props.dark) {
    ec?.getInstance()?.off("click");
    ec?.getInstance()?.on("click", params => {
      const { path, query } = toPageMap.get(params.name);
      if (!path) return;
      router.push({ path, query });
    });
  }
};
const toPage = () => {
  const path = "/all/alert/business";
  const query: any = { className: props.classCode, startTime, endTime };
  router.push({ path, query });
};
onMounted(async () => {
  // 今日报警
  await alarmStatInit();
});
/**
 * 定时用更新数据
 */
const initAll = async () => {
  alarmStatOptions.value = null;
  await alarmStatInit();
};
defineExpose({
  initAll
});
</script>
